<?php

namespace App\Http\Controllers\H5;

use App\Library\User\AddressTrait;
use App\Models\District;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends BaseController
{
    use AddressTrait;

    public function index()
    {
        $items = $this->user->addresses()->orderByDesc('isdefault')->get();
        return $this->view('h5.address.index', compact('items'));
    }

    public function getDistrictJson(){
        $array = cache()->remember('DistrictJSON', 1, function (){
            $districts = [];
            $items = District::whereIn('level', [1,2,3])->get(['id', 'fid', 'name'])->map(function ($dist) use (&$districts){
                $districts[$dist->fid][] = [
                    'label'=>$dist->name,
                    'value'=>$dist->id,
                ];
                return $dist;
            });

            return $this->formatDisteictArray($districts, 0);
        });

        return response()->json($array);
    }

    private function formatDisteictArray($array, $fid)
    {
        $newArray = [];
        foreach ($array[$fid] as $arr){
            $newArr = [
                'label'=>$arr['label'],
                'value'=>$arr['label']
            ];
            if (isset($array[$arr['value']])){
                $newArr['children'] = $this->formatDisteictArray($array, $arr['value']);
            }
            $newArray[] = $newArr;
        }
        return $newArray;
    }

    public function newAddress(Request $request)
    {

    }
}
